package com.egg.ylt.updateAppUtils;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;

import com.egg.ylt.activity.ACT_AppStart;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateAppVersionUtil {

    public final static int CAMERA_REQUEST_CODE = 0;
    public final static int INSTALL_PACKAGES_REQUESTCODE = 1;
    public final static int GET_UNKNOWN_APP_SOURCES = 2;

    //相关系统权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};
    private static File file;



    /**
     * 读取sd卡,动态申请权限
     */
    public static boolean requestPhotosPermissions(Context context, Activity activity) {
        //第二个参数是需要申请的权限
        if (ContextCompat.checkSelfPermission(context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 进入这儿表示没有权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
                // 提示已经禁止
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, CAMERA_REQUEST_CODE);
            } else {
                //权限还没有授予，需要在这里写申请权限的代码
                // 第二个参数是一个字符串数组，里面是你需要申请的权限 可以设置申请多个权限
                // 最后一个参数是标志你这次申请的权限，该常量在onRequestPermissionsResult中使用到
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, CAMERA_REQUEST_CODE);
            }

        } else { //权限已经被授予，在这里直接写要执行的相应方法即可
            return true;
        }
        return false;
    }

    /**
     * 下载apk进度条
     */
    public static void downLoadApk(final Context context, final Activity activity, final String updateUrl) {
        //进度条
        final ProgressDialog pd;
        pd = new ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.setCancelable(false);// 设置是否可以通过点击Back键取消
        pd.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        pd.setProgressNumberFormat("");//取消显示框右下角的数字
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    file = getFileFromServer(updateUrl, pd);
                    //安装APK
                    if (Build.VERSION.SDK_INT >= 26) {
                        boolean b = context.getPackageManager().canRequestPackageInstalls();
                        if (b) {
                            installApk(context);//安装应用的逻辑(写自己的就可以)
                            activity.finish();
                        } else {
                            //请求安装未知应用来源的权限
                            Uri packageURI = Uri.parse("package:"+context.getPackageName());
                            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
                            activity.startActivityForResult(intent, INSTALL_PACKAGES_REQUESTCODE);
//                            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_PACKAGES_REQUESTCODE);
                        }
                    } else {
                        installApk(context);
                    }
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    Log.e("Exception", e.toString());
                }
            }}.start();
    }

    /**
     * 下载apk
     * @param path
     * @param pd
     * @return
     * @throws Exception
     */
    public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len ;
            int total=0;
            while((len =bis.read(buffer))!=-1){
                fos.write(buffer, 0, len);
                total+= len;
                //获取当前下载量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        }
        else{
            return null;
        }
    }

    /**
     * 安装apk
     * @param
     */
    public static void installApk(Context context) {
        Uri uri;
        Intent intent = new Intent();
        //执行动作
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // 6.0以下
            uri = Uri.fromFile(file);
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { // 6.0 - 7.0
//            File apkFile = queryDownloadedApk(context, 0);
            uri = Uri.fromFile(file);
        } else { // Android 7.0 以上
            uri = FileProvider.getUriForFile(context, "com.egg.provider",
                    new File(Environment.getExternalStorageDirectory(), "updata.apk"));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        }

        //执行的数据类型
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);

    }

    //通过downLoadId查询下载的apk，解决6.0以后安装的问题
    public static File queryDownloadedApk(Context context, long downloadId) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }
}
